package com.lv.fast.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.lv.fast.DTO.SysLoginDTO;
import com.lv.fast.DTO.SysUserDTO;
import com.lv.fast.constant.UserConstant;
import com.lv.fast.enums.UserStatusEnum;
import com.lv.fast.service.SysLoginService;
import com.lv.fast.service.SysUserService;
import com.lv.fast.util.Assert;
import com.lv.fast.util.JwtUtil;
import com.lv.fast.util.SysUserUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Description
 * @Author jie.lv
 */
@Service
@AllArgsConstructor
public class SysLoginServiceImpl implements SysLoginService {

    private final SysUserService sysUserService;

    @Override
    public Optional<String> login(SysLoginDTO sysLoginDTO){
        Assert.assertNotNull(sysLoginDTO, "登录对象不能为空");
        SysUserDTO userDTO = sysUserService.getSysUserByUniqueKey(sysLoginDTO.getKey());
        if (userDTO == null || userDTO.getStatus().equals(UserStatusEnum.DELETED.getCode())){
            return Optional.empty();
        }
        if (userDTO.getStatus().equals(UserStatusEnum.LOCK.getCode())){
            return Optional.ofNullable(UserConstant.JSON_KEY);
        }
        if (!BCrypt.checkpw(sysLoginDTO.getPassword(), userDTO.getPassword().toLowerCase())){
            return Optional.empty();
        }
        String token = JwtUtil.generateToken(userDTO.getId());
        // 写缓存
        SysUserUtil.addUserPassword(userDTO.getId(), userDTO.getPassword());
        return Optional.ofNullable(token);
    }
}
